package com.owner.lt.tool.tool;

import com.owner.lt.tool.utils.IOUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;


public class ZipTool {
    private static final Logger log = LoggerFactory.getLogger(ZipTool.class);
    /**
     * 操作流的时候指定一次读取多少字节，设置大一些压缩大文件会快一些
     */
    private static final int BUFFER_SIZE = 8 * 1024;

    /**
     * 合并多个zip文件的内容
     * @param tartetZipFile 合并后的zip文件
     * @param sourceZipFiles 需要合并的zip文件列表
     * @return 是否成功
     */
    public static boolean mergeZips(String tartetZipFile, List<String> sourceZipFiles) {
        boolean flag = true;
        ZipOutputStream out = null;
        List<ZipInputStream> ins = new ArrayList<ZipInputStream>();
        DataInputStream dis = null;
        List<FileInputStream> fis = new ArrayList<FileInputStream>();
        FileOutputStream fos = null;
        List<ZipFile> zipFiles = new ArrayList<ZipFile>();
        try {
            fos = new FileOutputStream(tartetZipFile);
            out = new ZipOutputStream(fos);
            HashSet<String> names = new HashSet<String>();
            for (String sourceZipFile : sourceZipFiles) {
                ZipFile zipFile = new ZipFile(sourceZipFile, Charset.forName("GBK"));
                FileInputStream fileInputStream = new FileInputStream(sourceZipFile);
                ZipInputStream zipInputStream = new ZipInputStream(fileInputStream);
                fis.add(fileInputStream);
                ins.add(zipInputStream);
                zipFiles.add(zipFile);
                ZipEntry ze;
                Enumeration<? extends ZipEntry> enumeration = zipFile.entries();
                while (enumeration.hasMoreElements()) {
                    ze = enumeration.nextElement();
                    if (!ze.isDirectory()) {
                        if (names.contains(ze.getName())) {
                            continue;
                        }
                        ZipEntry oze = new ZipEntry(ze.getName());
                        out.putNextEntry(oze);
                        if (ze.getSize() > 0) {
                            dis = new DataInputStream(zipFile.getInputStream(ze));
                            int len = 0;
                            byte[] bytes = new byte[1024];
                            while ((len = dis.read(bytes)) > 0) {
                                out.write(bytes, 0, len);
                            }
                            out.closeEntry();
                            out.flush();
                        }
                        names.add(oze.getName());
                    }
                }
                flag = true;
            }
        } catch (Exception e) {
            flag = false;
        } finally {
            IOUtils.closeQuietly(out, fos, dis);
            IOUtils.closeQuietly(fis);
            IOUtils.closeQuietly(ins);
            IOUtils.closeQuietly(zipFiles);
        }
        return flag;
    }

    /**
     * 压缩成ZIP 方法1
     *
     * @param srcDir           压缩文件夹路径
     * @param out              压缩文件输出流
     * @param KeepDirStructure 是否保留原来的目录结构,true:保留目录结构;
     *                         false:所有文件跑到压缩包根目录下(注意：不保留目录结构可能会出现同名文件,会压缩失败)
     * @throws RuntimeException 压缩失败会抛出运行时异常
     */
    public static void toZip(String srcDir, OutputStream out, boolean KeepDirStructure) {
        long start = System.currentTimeMillis();
        ZipOutputStream zos = null;
        try {
            zos = new ZipOutputStream(out);
            File sourceFile = new File(srcDir);
            compress(sourceFile, zos, sourceFile.getName(), KeepDirStructure);
            long end = System.currentTimeMillis();
            log.info("zip压缩完成，耗时：{}ms", (end - start));
        } catch (Exception e) {
            throw new RuntimeException("zip error from ZipUtils", e);
        } finally {
            IOUtils.closeQuietly(zos);
        }

    }

    /**
     * 压缩成ZIP 方法2
     *
     * @param srcFiles 需要压缩的文件列表
     * @param out      压缩文件输出流，直接用FileOutputStream即可
     * @throws RuntimeException 压缩失败会抛出运行时异常
     */
    public static void toZip(List<File> srcFiles, OutputStream out) throws RuntimeException {
        long start = System.currentTimeMillis();
        ZipOutputStream zos = null;
        FileInputStream in = null;
        try {
            zos = new ZipOutputStream(out);
            for (File srcFile : srcFiles) {
                byte[] buf = new byte[BUFFER_SIZE];
                zos.putNextEntry(new ZipEntry(srcFile.getName()));
                int len;
                in = new FileInputStream(srcFile);
                while ((len = in.read(buf)) != -1) {
                    zos.write(buf, 0, len);
                }
                zos.closeEntry();
            }
            long end = System.currentTimeMillis();
            log.info("zip压缩完成，耗时：{}ms", (end - start));
        } catch (IOException e) {
            throw new RuntimeException("zip error from ZipUtils", e);
        } finally {
            IOUtils.closeQuietly(zos, in);
        }
    }


    /**
     * 递归压缩方法
     *
     * @param sourceFile       源文件
     * @param zos              zip输出流
     * @param name             压缩后的名称
     * @param KeepDirStructure 是否保留原来的目录结构,true:保留目录结构;
     *                         false:所有文件跑到压缩包根目录下(注意：不保留目录结构可能会出现同名文件,会压缩失败)
     * @throws Exception
     */
    private static void compress(File sourceFile, ZipOutputStream zos, String name,
                                 boolean KeepDirStructure) throws Exception {
        byte[] buf = new byte[BUFFER_SIZE];
        if (sourceFile.isFile()) {
            // 向zip输出流中添加一个zip实体，构造器中name为zip实体的文件的名字
            zos.putNextEntry(new ZipEntry(name));
            // copy文件到zip输出流中
            int len;
            try(FileInputStream in = new FileInputStream(sourceFile);){
                while ((len = in.read(buf)) != -1) {
                    zos.write(buf, 0, len);
                }
                // 关闭当前ZIP条目并定位流以写入下一个条目，不关就还是这一个条目
                zos.closeEntry();
            }catch (Exception e){
                throw new RuntimeException("zip error from ZipUtils", e);
            }
        } else {
            File[] listFiles = sourceFile.listFiles();
            if (listFiles == null || listFiles.length == 0) {
                // 需要保留原来的文件结构时,需要对空文件夹进行处理
                if (KeepDirStructure) {
                    // 空文件夹的处理
                    zos.putNextEntry(new ZipEntry(name + "/"));
                    // 没有文件，不需要文件的copy
                    zos.closeEntry();
                }

            } else {
                for (File file : listFiles) {
                    // 判断是否需要保留原来的文件结构
                    if (KeepDirStructure) {
                        // 注意：file.getName()前面需要带上父文件夹的名字加一斜杠,
                        // 不然最后压缩包中就不能保留原来的文件结构,即：所有文件都跑到压缩包根目录下了
                        compress(file, zos, name + "/" + file.getName(), KeepDirStructure);
                    } else {
                        compress(file, zos, file.getName(), KeepDirStructure);
                    }
                }
            }
        }
    }

    public static void main(String[] args) throws Exception {
        /** 测试压缩方法1  */
        FileOutputStream fos1 = new FileOutputStream("D:\\testZip1.zip");
        toZip("D:\\logs", fos1, false);

        /** 测试压缩方法2  */
        List<File> fileList = new ArrayList<>();
        fileList.add(new File("D:\\logs\\dsp\\command-center.log.2023-12-26.0"));
        fileList.add(new File("D:\\logs\\axax.zip"));
        FileOutputStream fos2 = new FileOutputStream("D:\\testZip2.zip");
        toZip(fileList, fos2);
    }
}
